﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks; 
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace UFIDA.U8C.AnLianDB
{
    public class common
    { 
        //读取App.config的值
        public static string getConfigInfo(string key)
        {
            string value = "";
            value = ConfigurationManager.AppSettings[key];
            return value;
        }

        //设置App.config的值
        public static bool setConfigInfo(string key, string value)
        {
            try
            {
                Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                configuration.AppSettings.Settings[key].Value = value;
                configuration.Save();

                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string mysqlconn()
        {
            return "Server = " + getConfigInfo("hxserver") + ";User = " + getConfigInfo("hxuser") + "; password = " + getConfigInfo("hxpsd") + ";Database = " + getConfigInfo("hxsid") +";Charset=utf8";
        }

        public static string u8cconn()
        {
            //
            //return "User Id=" + getConfigInfo("u8cuser") + ";Password=" + getConfigInfo("u8cpsd") + ";Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" + getConfigInfo("u8cserver") + ")(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=" + getConfigInfo("u8csid") + ")))";
            //return "Data Source  = " + getConfigInfo("u8cserver") + ";User Id = " + getConfigInfo("u8cuser") + "; Password = " + getConfigInfo("u8cpsd") + ";Initial Catalog = " + getConfigInfo("u8csid");
            return "Server = " + getConfigInfo("u8cserver") + ";User = " + getConfigInfo("u8cuser") + "; Pwd = " + getConfigInfo("u8cpsd") + ";Database = " + getConfigInfo("u8csid"); 
        }

        public static string bankconn()
        {
            return "Server = " + getConfigInfo("bankserver") + ";User = " + getConfigInfo("bankuser") + "; Pwd = " + getConfigInfo("bankpsd") + ";Database = " + getConfigInfo("banksid"); 
        }

        public static string getu8copera()
        {
            return getConfigInfo("u8copera");
        }
        public static string getu8coppsd()
        {
            string psd = getConfigInfo("u8coppsd");
            if (!string.IsNullOrEmpty(psd))
            {
                //return UFIDA.U8.PUB.EncryptDecryptService.DESEncrypt(UFIDA.U8.PUB.EncryptDecryptService.strDESKey, psd);
                return MD5(psd);
            }
            else
            {
                return "";
            }      
        }


        public static string MD5(string strPwd)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(strPwd));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++ )
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }       
            return sb.ToString();
        }

        public static bool PostU8C(string uniquekey, string json, string url,ref string resResult, ref string errMsg)
        {
            Dictionary<String, string> mapHead = new Dictionary<string, string>();
            try
            {
                mapHead.Add("Accept-Language", "zh-cn"); 
                mapHead.Add("usercode", getu8copera());
                mapHead.Add("password", getu8coppsd());
                mapHead.Add("uniquekey", uniquekey);
                mapHead.Add("system", "SYJ");

                string responseContent = PostHttpHelper.PostHttp(url, mapHead, json, "application/json", 60000);

                U8CRespone res = JsonConvert.DeserializeObject<U8CRespone>(responseContent);
                if (!res.status.Equals("success"))
                {
                    errMsg = res.errormsg;
                    return false;
                }
                resResult = res.data;
                return true;
            }
            catch(Exception ex)
            {
                errMsg = ex.Message;
                throw ex;
            } 
        }
        
        
        /// <summary>        
        /// 转全角(SBC case)        
        /// </summary>        
        /// <param name="input">任意字符串</param>        
        /// <returns>全角字符串</returns>       
        public static string ToSBC(string input)        
        {            
            char[] c = input.ToCharArray();            
            for (int i = 0; i < c.Length; i++)            
            {                
                if (c[i] == 32)                
                {                    
                    c[i] = (char)12288;                    
                    continue;                
                }                
                if (c[i] < 127)                   
                    c[i] = (char)(c[i] + 65248);            
            }            return new string(c);        
        }        
        /// <summary>        
        /// 转半角(DBC case)        
        /// </summary>        
        /// <param name="input">任意字符串</param>       
        /// /// <returns>半角字符串</returns>        
        public static string ToDBC(string input)        
        {            
            char[] c = input.ToCharArray();            
            for (int i = 0; i < c.Length; i++)            
            {                
                if (c[i] == 12288)                
                {                    
                    c[i] = (char)32;                    
                    continue;                
                }                
                if (c[i] > 65280 && c[i] < 65375)                    
                    c[i] = (char)(c[i] - 65248);            
            }            
            return new string(c);        
        }
        
        public static string getcubasdoc(string Name, ref string custclass, string conn)
        {
            string sql = "select a.custcode, b.docname from bd_cubasdoc a left join bd_defdoc b on b.PK_DEFDOC = a.def2  where a.custname ='" + ToDBC(Name) + "' or a.custname = '" + ToSBC(Name) + "'";
            DataTable dt = UFIDA.NC.DB.DbHelperSQL_Ora.QueryDTOra(sql,"", conn);
            if (dt!=null && dt.Rows.Count > 0)
            {
                custclass = dt.Rows[0]["docname"].ToString();
                return dt.Rows[0]["custcode"].ToString();
            }

            return "";
        }


        public static DataSet GetU8CCorp()
        {
            string sql = "select unitcode, unitname from bd_corp";
            return UFIDA.NC.DB.DbHelperSQL_Ora.QueryDsByOra(sql, "orgs", u8cconn());
        }


        /// <summary>
        /// 同步项目档案
        /// </summary>
        public static bool SyncJob()
        {
            try
            {
                string sql = "delete from bd_jobbasfil";
                UFIDA.U8.DB.DbHelperSQL.ExecuteSql(sql, common.bankconn());
                sql = "select jobcode, jobname  from bd_jobbasfil ";
                DataTable dt = UFIDA.NC.DB.DbHelperSQL_Ora.QueryDTOra(sql, "bd_jobbasfil", common.u8cconn());
                if (dt != null & dt.Rows.Count > 0)
                {
                    UFIDA.U8.DB.DbHelperSQL.ImportDataByDataTable(dt, "bd_jobbasfil", common.bankconn());
                }
                return true;
            }
            catch (Exception ex)
            {
                throw;
            } 
        }

        public static Newtonsoft.Json.Linq.JToken GetU8CGlorgBook(string corp)
        {
            string sql = "select top 1 glorgbook  from cust_accconfig where corp = '"+ corp +"'";
            DataTable dt = UFIDA.U8.DB.DbHelperSQL.QueryAsDT(sql, common.bankconn());
            if (dt!= null && dt.Rows.Count > 0)
            {
                return dt.Rows[0]["glorgbook"].ToString();
            }
            return "";
        }
    }


    public class PostHttpHelper
    {
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受
        }

        //body是要传递的参数,格式"roleId=1&uid=2"
        //post的cotentType填写:
        //"application/x-www-form-urlencoded"
        //soap填写:"text/xml; charset=utf-8"
        //timeout 填写超时毫秒
        public static string PostHttp(string url, Dictionary<string, string> headerdic, string body, string contentType, int timeout)
        {
            string responseContent = String.Empty; 
            HttpWebRequest httpWebRequest = null;  
            try
            {
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    ServicePointManager.CheckCertificateRevocationList = true;
                    ServicePointManager.DefaultConnectionLimit = 100;
                    ServicePointManager.Expect100Continue = true;
                    httpWebRequest = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
                    httpWebRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    httpWebRequest = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
                }

                if (headerdic != null && headerdic.Count > 0)
                {
                    foreach (var item in headerdic)
                    {
                        httpWebRequest.Headers.Add(item.Key, item.Value);
                    }
                }

                httpWebRequest.ContentType = contentType;
                httpWebRequest.Method = "POST";
                httpWebRequest.Timeout = timeout;
                httpWebRequest.ServicePoint.Expect100Continue = false;
                httpWebRequest.ServicePoint.ConnectionLimit = 500;

                byte[] btBodys = Encoding.UTF8.GetBytes(body);
                httpWebRequest.ContentLength = btBodys.Length;

                httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
                using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {


                    Stream responseStream = httpWebResponse.GetResponseStream();

                    if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                        responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                    else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                        responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                    Encoding encoding;
                    //if (httpWebResponse.CharacterSet.ToUpper().Contains("ISO-8859-1"))
                    //    encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                    //else
                    encoding = Encoding.UTF8;
                    //encoding = Encoding.GetEncoding("GBK");
                    StreamReader streamReader;
                    streamReader = new StreamReader(responseStream, encoding, true);
                    String resultstr = streamReader.ReadToEnd();

                    resultstr = System.Web.HttpUtility.UrlDecode(resultstr);
                    responseContent = resultstr;

                    httpWebResponse.Close();
                    streamReader.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }
            }


            return responseContent;
        }
    }
 }
